#!/usr/bin/env bash

# shellcheck disable=SC2162
# shellcheck disable=SC2015
# shellcheck disable=SC2016
# shellcheck disable=SC2046
# shellcheck disable=SC2060

out_yellow() {
    echo -e "\033[33m$1\033[0m"
}

out_pink() {
    echo -e "\033[35m$1\033[0m"
}

out_cyan() {
    echo -e "\033[36m$1\033[0m"
}

[ ! -d "/data/mcdn" ] && mkdir /data/mcdn

{

    # 首先要知道这台B站是客户的还是咱们自建的
    # _is_customer 为1表示客户，为0表示咱们自建
    read -p ">>>  这是客户的设备吗? [Y/N] 默认Y: " _is_customer

    _status=$(echo "$_is_customer" | grep -ic "y")

    [[ -z "$_is_customer" || $_status -eq 1 ]] && _is_customer=1 || _is_customer=0
}

{

    while true; do
        # 需要知道这台设备使用的是汇聚线路还是专线，如果是专线汇聚也属于汇聚线路
        read -p ">>>  这是? [电联-专线=1, 电联-汇聚=2, 移动-专线=3, 移动-汇聚=4] 无默认: " _bandwidth_type

        # {
        #     "data": {
        #         "queryPCDNProjects": [
        #             {
        #                 "id": "0x2f10d3ba",
        #                 "name": "MCDN专线-日常补点项目-外采" 移动-专线
        #             },
        #             {
        #                 "id": "0x2f263046",
        #                 "name": "MCDN汇聚-日常补点项目-外采" 移动-汇聚
        #             },
        #             {
        #                 "id": "0x3444a7e9",
        #                 "name": "MCDN汇聚-合池日常交付-外采" 电联-汇聚
        #             },
        #             {
        #                 "id": "0x3444b27a",
        #                 "name": "MCDN专线-合池日常交付-外采" 电联-专线
        #             }
        #         ]
        #     }
        # }

        case "${_bandwidth_type}" in
        1)
            _project_id="0x2f10d3ba" # 0x3444b27a
            work_type="v"            # 合池属于v业务
            ;;
        2)
            _project_id="0x3444a7e9"
            work_type="v" # 合池属于v业务
            ;;
        3)
            _project_id="0x2f10d3ba" # 0x2f4e169b
            work_type="mp2sp"        # 日常补点项目属于mp2sp业务
            ;;
        4)
            _project_id="0x2f263046"
            work_type="mp2sp" # 日常补点项目属于mp2sp业务
            ;;
        esac

        [[ "$_bandwidth_type" -ne 1 && "$_bandwidth_type" -ne 2 && "$_bandwidth_type" -ne 3 && "$_bandwidth_type" -ne 4 ]] && out_pink ">>> 输入错误，请重新输入" || break

    done

}

{
    # 如果是专线资源，那么需要提供这条专线的带宽是多大的
    if [[ "$_bandwidth_type" -eq 1 || "$_bandwidth_type" -eq 3 ]]; then

        while true; do
            read -p ">>>  请输入专线的带宽 [如100, 1000] 无默认: " _upBandwidth

            _NumberDialUpLines="1"
            _singleLineCapacity="$_upBandwidth"

            [ -z "$_upBandwidth" ] && out_pink ">>> 专线的带宽不能为空" || break

        done

    else

        # 如果是汇聚资源，那么需要提供这台设备的汇聚线路数量和单线容量

        while true; do
            read -p ">>>  请输入汇聚线路数量 [有几条线路就输入几]: " _NumberDialUpLines

            [ -z "$_NumberDialUpLines" ] && out_pink ">>> 汇聚线路数不能为空" || break

        done

        while true; do
            read -p ">>>  请输入单线带宽 [单位是Mb] 无默认: " _singleLineCapacity

            [ -z "$_singleLineCapacity" ] && out_pink ">>> 单线带宽容量不能为空" || break

        done

        _upBandwidth=$(echo "$_singleLineCapacity * $_NumberDialUpLines" | bc)

    fi
}

{
    if [ "$_is_customer" -eq 1 ]; then

        while true; do
            # 如果这是客户的机器，那还需要知道客户的名字，用于设置主机名，必须提供，并且不可重复的
            echo ">>>  客户名称格式为 手机尾号后4位加编号, 如8888001, 001表示这个客户的第一台B站,第二台是002]"

            read -p ">>>  客户名称 [介绍如上] 无默认: " _user_name

            [ -z "$_user_name" ] && out_pink ">>> 客户的名称不能为空" || break
        done

    else

        # 如果是咱们自建的机器，那就直接用IPMI工具获取IP地址作为主机名
        _user_name=$(ipmitool lan print 2>/dev/null | grep -P '(^IP Address).+?([0-9])' | awk '{print $NF}' | awk -F '.' '{print $1,$2,$3}' | tr -d '[:space:]')

    fi
}

{
    # 得到设备类型
    read -p ">>>  设备类型 [ARM32=1, ARM64=2, X86=3] 默认X86: " _input_device_type

    [ -z "$_input_device_type" ] && _input_device_type=3

    case "${_input_device_type}" in
    1)
        _device_type="ARM32"
        ;;
    2)
        _device_type="ARM64"
        ;;
    3)
        _device_type="X86"
        ;;
    esac

}

{

    while true; do

        # 得到计费类型
        read -p ">>>  计费类型 [汇聚=1, 专线=2, 汇聚-移动内网=3] 无默认: " _input_charge_type

        case "${_input_charge_type}" in
        1)
            _charge_type="0x274db73f"
            ;;
        2)
            _charge_type="0x274db740"
            ;;
        3)
            _charge_type="0x274db741"
            ;;
        esac

        [[ "$_input_charge_type" -ne 1 && "$_input_charge_type" -ne 2 && "$_input_charge_type" -ne 3 ]] && out_pink ">>> 计费类型不能为空" || break

    done

}

{
    # 得到调度类型
    read -p ">>>  调度范围 [全国=1, 省内=2] 默认全国: " _input_schedScope

    [ -z "$_input_schedScope" ] && _input_schedScope=2

    [ "$_input_schedScope" -eq 1 ] && _schedScope="global" || _schedScope="province"

}

# ============================================================================================================
# ============================================================================================================
# ============================================================================================================
# 汉字转换到拼音
chineseCharactersToPinyin() {
    _respond=$(curl -sSL -X 'POST' 'https://openapi.lddgo.net/base/gservice/api/v1/PinyinFirstLetter' \
        -H 'Content-Type: application/json;charset=UTF-8' -H 'Accept: */*' \
        -d '{"data":"'"$1"'","multi":false,"unKnown":"default","case":"lower"}')

    echo "$_respond" | jq --raw-output '.data[] | select(.type == "pinyin") | .data ' | tr -d '\n'

    # {"code":0,"msg":null,"data":[{"data":"h","type":"pinyin"},{"data":"n","type":"pinyin"},{"data":"  ","type":"raw"},{"data":"y","type":"pinyin"},{"data":"z","type":"pinyin"}]}
}

# ============================================================================================================
# ============================================================================================================
# ============================================================================================================

# 设置主机名
set_hostname() {
    # mcdn-bdwl-zjsx-dx-v-Xx03

    # root@mcdn-bdwl-zjsx-dx-v-Xx03:~# curl -sSL cip.cc
    # IP	: 115.237.136.95
    # 地址	: 中国  浙江  绍兴
    # 运营商	: 电信

    # 数据二	: 浙江省绍兴市 | 电信

    # 数据三	: 中国浙江省绍兴市 | 电信

    # URL	: http://www.cip.cc/115.237.136.95

    _host_info=$(timeout 10 curl -sSL myip.ipip.net)

    _operator=$(echo "$_host_info" | awk '{print $NF}' | tr -d '[:space:]')

    # 省份名称
    _region_prov=$(echo "$_host_info" | awk '{print $4}' | tr -d '[:space:]')

    # 城市
    _region_city=$(echo "$_host_info" | awk '{print $5}' | tr -d '[:space:]')

    # 通过中文地址转换到拼写的首字母
    _region_spell=$(chineseCharactersToPinyin "$_region_prov $_region_city")

    # 运营商类型 移动=cmcc，电信=dx，联通=cu
    case "${_operator}" in
    "电信")
        _operator_abbr="dx"
        _operator_id="0x274df24c"
        ;;

    "移动")
        _operator_abbr="cmcc"
        _operator_id="0x274df24b"
        ;;

    "联通")
        _operator_abbr="cu"
        _operator_id="0x274df24d"
        ;;
    esac

    _hostname="mcdn-bdwl-$_region_spell-$_operator_abbr-$work_type-$_user_name"
}

# 获取主机SN
get_host_sn() {

    _host_sn="$(dmidecode -s system-serial-number)"

}

# 获取主机型号
get_host_model() {

    _host_model=$(dmidecode -t system | grep -i 'Product Name' | awk '{print $NF}')

}

# 获取CPU型号
get_host_cpu_model() {
    _host_cpu_model=$(awk -F ':' '/^model name/{print $NF}' /proc/cpuinfo | head -n1)
}

# 获取内存型号
get_host_memory() {
    _host_memory=$(dmidecode 2>/dev/null | grep '^\sType\:\sDDR' | awk '{print $NF}' | sort -n | uniq -c | awk '{print $2}')
}

# 获取省份
get_province() {

    # _respond=$(agency_curl 'proxy' '{"query":"query($where:ProvinceWhere){queryProvinces(where:$where){name area{name} id}}","variables":{"where":{"area":{"country":{"id":"0x274df47b"}}}}}')

    _respond='{"data":{"queryProvinces":[{"area":{"name":"港澳台地区"},"id":"0x16c92b9f","name":"澳门"},{"area":{"name":"西南地区"},"id":"0x16c92ba0","name":"重庆"},{"area":{"name":"华中地区"},"id":"0x16c92ba1","name":"湖北"},{"area":{"name":"华南地区"},"id":"0x16c92ba2","name":"福建"},{"area":{"name":"华东地区"},"id":"0x16c92ba3","name":"江苏"},{"area":{"name":"华中地区"},"id":"0x16c92ba4","name":"江西"},{"area":{"name":"西南地区"},"id":"0x16c92ba5","name":"四川"},{"area":{"name":"西北地区"},"id":"0x16c92ba6","name":"陕西"},{"area":{"name":"东北地区"},"id":"0x16c92ba7","name":"辽宁"},{"area":{"name":"华东地区"},"id":"0x16c92ba8","name":"浙江"},{"area":{"name":"华北地区"},"id":"0x16c92ba9","name":"山东"},{"area":{"name":"西北地区"},"id":"0x16c92baa","name":"宁夏"},{"area":{"name":"东北地区"},"id":"0x16c92bab","name":"吉林"},{"area":{"name":"华东地区"},"id":"0x16c92bac","name":"上海"},{"area":{"name":"华南地区"},"id":"0x16c92bae","name":"广西"},{"area":{"name":"西北地区"},"id":"0x16c92baf","name":"青海"},{"area":{"name":"西北地区"},"id":"0x16c92bb0","name":"新疆"},{"area":{"name":"华北地区"},"id":"0x16c92bb1","name":"内蒙古"},{"area":{"name":"华北地区"},"id":"0x16c92bb2","name":"河北"},{"area":{"name":"华南地区"},"id":"0x16c92bb3","name":"广东"},{"area":{"name":"华中地区"},"id":"0x16c92bb4","name":"河南"},{"area":{"name":"西南地区"},"id":"0x16c92bb5","name":"云南"},{"area":{"name":"西北地区"},"id":"0x16c92bb6","name":"甘肃"},{"area":{"name":"华北地区"},"id":"0x16c92bb7","name":"天津"},{"area":{"name":"港澳台地区"},"id":"0x16c92bb8","name":"香港"},{"area":{"name":"东北地区"},"id":"0x16c92bb9","name":"黑龙江"},{"area":{"name":"华北地区"},"id":"0x16c92bba","name":"山西"},{"area":{"name":"华南地区"},"id":"0x16c92bbb","name":"海南"},{"area":{"name":"华中地区"},"id":"0x16c92bbc","name":"湖南"},{"area":{"name":"西南地区"},"id":"0x16c92bbd","name":"贵州"},{"area":{"name":"西南地区"},"id":"0x16c92bbe","name":"西藏"},{"area":{"name":"港澳台地区"},"id":"0x16c92bbf","name":"台湾"},{"area":{"name":"华北地区"},"id":"0x16c92bc0","name":"北京"},{"area":{"name":"华东地区"},"id":"0x289fad23","name":"安徽"}]}}'

    echo "获取省份 : $_region_prov"

    _province="$(echo "$_respond" | jq -r --raw-output '.data.queryProvinces[] | select(.name == "'"$_region_prov"'") | .id')"
}

# 格式化磁盘
format_disk() {
    __dl() {
        mkdir -p /tmp/perccli
        curl -o - 'https://dl.dell.com/FOLDER09770976M/1/PERCCLI_7.2313.0_A14_Linux.tar.gz' \
            -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36' 2>/dev/null | tar zxvf - --strip-components=1 -C /tmp/perccli

    }

    __main() {
        __dl
        _os=$(grep -E 'debian|centos|ubuntu' -o /etc/os-release | uniq)
        case "${_os}" in
        centos)
            ! rpm -qa | grep perccli || exit 1
            rpm --import /tmp/perccli/pubKey.asc
            rpm -i /tmp/perccli/*.rpm
            ln -s /opt/MegaRAID/perccli/perccli64 /usr/local/bin/
            ;;
        debian | ubuntu)
            ! dpkg-query -W '*perccli*' || exit 1
            dpkg -i /tmp/perccli/*.deb
            ln -s /opt/MegaRAID/perccli/perccli64 /usr/local/bin/
            ;;
        *)
            echo "not found os "
            ;;
        esac
        rm -rf /tmp/perccli
    }
    __main

    __disk_raid_create() {
        echo "重组阵列"
        perccli64CmdOutput=$(perccli64 /c0/eall/sall show J)
        ugoodDisks=$(echo "$perccli64CmdOutput" | jq -r '.Controllers[0]."Response Data"."Drive Information"[] | select(.State == "UGood" and .Med == "HDD") | .["EID:Slt"]')
        # 检查是否有 UGood 状态的磁盘
        if [ -n "$ugoodDisks" ]; then
            # 删除所有现有的虚拟磁盘
            perccli64 /c0/fall del &>/dev/null

            # 为每个 UGood 状态的磁盘创建 RAID 0
            for disk in $ugoodDisks; do
                eid=${disk%:*}
                slot=${disk#*:}
                echo "正在为 EID ${eid}, Slot ${slot} 的磁盘创建 RAID 0..."
                perccli64 /c0 add vd r0 drives="${eid}":"${slot}" wb ra &>/dev/null
            done
        else
            echo "没有找到任何 UGood 状态的磁盘。"
        fi
    }
    __disk_raid_create

    lsblk --noheadings -d | awk '{print "/dev/"$1}' | grep -v "$(df -h / | tail -n1 | awk '{print $1}' | tr -d [0-9])" | xargs -I {} -P $(nproc) mkfs.xfs -f {}
}

# 创建JSON主体,最终提交的时候就是提交这坨JSON
create_json_body() {

    _json_body='
{
    "query": "mutation($input: [FormCreatePCDNAssetsCreate!]!){upsertFormCreatePCDNAssetss(input:$input){nodeCreated formcreatepcdnassetss{id job{id}}}}",
    "variables": {
        "input": [
            {
                "name": "'"$_hostname"'",
                "sn": "'"$_host_sn"'",
                "deviceType": "'"$_device_type"'",
                "category": {
                    "id": "'"$_charge_type"'"
                },
                "country": {
                    "id": "0x274df47b"
                },
                "province": {
                    "id": "'"$_province"'"
                },
                "operator": {
                    "id": "'"$_operator_id"'"
                },
                "project": {
                    "id": "'"$_project_id"'"
                },
                "model": "'"$_host_model"'",
                "schedScope": "'"$_schedScope"'",
                "upBandwidth": "'"$_upBandwidth"'",
                "NumberDialUpLines": "'"$_NumberDialUpLines"'",
                "singleLineCapacity": "'"$_singleLineCapacity"'",
                "loginPort": 22,
                "cpuModel": "'"$_host_cpu_model"'",
                "memoryModel": "'"$_host_memory"'",
                "disk": "磁盘阵列",
                "raid": "730mini",
                "remark": "客户",
                "formName": ""
            }
        ]
    }
}
'

    echo "$_json_body" >/data/mcdn/config.json

}

main() {
    set_hostname
    get_host_sn
    get_host_model
    get_host_cpu_model
    get_host_memory
    get_province

    create_json_body
}
main

{
    # 设置主机名
    hostnamectl set-hostname --static "$_hostname"

    # 写入公钥
    key="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICXNRgvZxkBSWH6gg0QQWLO2EfkQozoPa+GK8OR7Xrwr bd-idc-202309020"
    key_path="/root/.ssh/authorized_keys"

    if [ "$(awk 'NF' "$key_path" | grep "$key" -c)" -eq 0 ]; then

        echo "$key" >>"$key_path"

    fi
}

{
    awk 'NF' /data/mcdn/config.json | jq

    out_cyan ">>> 单线容量：$_singleLineCapacity"
    out_cyan ">>> 线路数量：$_NumberDialUpLines"
    out_cyan ">>> 带宽总量：$_upBandwidth"

    out_yellow ">>> 主机名：$_hostname"
    out_cyan ">>> 请确认以上信息是否有空缺，若无异常请执行提交脚本"
    out_cyan ">>> 注意, 记得按照文档的要求, 将rtty客户端以及管理容器安装上"
}

: <<!

    bash -c "$(curl -sSL https://gitea.kuaicdn.cn/Reverse/work-script/raw/branch/main/idc/app/blink/config.sh)"

!